package com.yixun.qfbao.api.service.impl;

import com.yixun.qfbao.api.service.InitDataService;
import com.yixun.qfbao.api.service.WxTemplateMsgService;
import com.yixun.qfbao.apidto.InitDataReqDto;
import com.yixun.qfbao.apidto.InitDataResDto;
import com.yixun.qfbao.apidto.SendWXMsgAgainReqDto;
import com.yixun.qfbao.apidto.SendWXMsgAgainResDto;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.CompanyWxconfig;
import com.yixun.qfbao.model.Subscription;
import com.yixun.qfbao.model.WxmsgModel;
import com.yixun.qfbao.model.dto.CompanyWxconfigDto;
import com.yixun.qfbao.model.dto.SubscriptionDto;
import com.yixun.qfbao.model.dto.WxmsgModelDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.InitTypeEnum;
import com.yixun.qfbao.model.enums.WXModelTypeEnum;
import com.yixun.qfbao.model.enums.WxConfigEnum;
import com.yixun.qfbao.service.CompanyWxconfigService;
import com.yixun.qfbao.service.SubscriptionService;
import com.yixun.qfbao.service.WxmsgModelService;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * [文件名称]<br>
 * PremisesServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 楼盘接口<br>
 * <br>
 *
 * @author jzliu
 * @version 1.00
 */
@Service
public class InitDataServiceImpl implements InitDataService {

	private static final Logger logger = LoggerFactory.getLogger(InitDataServiceImpl.class);

	@Autowired
	private SubscriptionService subscriptionService;
	@Autowired
	private WxmsgModelService wxmsgModelService;
	@Autowired
    private CompanyWxconfigService companyWxconfigService;
	@Autowired
	private WxTemplateMsgService wxTemplateMsgService;
	@Autowired
	private CustomerPremisesService customerPremisesService;

	/**
	 * 根据类型初始化数据
	 * @param reqDto
	 * @return
	 */
	@Override
	public InitDataResDto initData(InitDataReqDto reqDto) {
		InitDataResDto resDto = new InitDataResDto();
		List<String> companyUuids = reqDto.getCompanyUuids();
		List<Company> companyList = reqDto.getCompanyList();
		String initType = reqDto.getInitType();
		if(InitTypeEnum.TYPE_ONE.getNo().equals(initType)){
			resDto = initWxConfig(companyList);
		}else if(InitTypeEnum.TYPE_TWO.getNo().equals(initType)){
			resDto = initWxTemplateMsg(companyUuids, companyList);
		}
		return resDto;
	}

	/**
	 * 初始化微信配置
	 * 根据公司去匹配微信的设置记录.不存在进行添加.
	 * 此处不做任何修改操作
	 * @return
	 */
	public InitDataResDto initWxConfig(List<Company> companyList){
		InitDataResDto resDto = new InitDataResDto();
		Map<String, Subscription> subMap = getSubscriptionMap();
		String[] systemIds = {"2", "3"};
		for(Company company: companyList){
			String companId = String.valueOf(company.getId());
			String companyUuid = company.getCompanyUuid();
			String appId = company.getAppId();
			String appSecret = company.getAppSecret();
			if(StringUtils.isBlank(appId) || StringUtils.isBlank(appSecret) || StringUtils.isBlank(companyUuid)){
				continue;
			}
			for(String systemId: systemIds){
				String key = companId + "-" + companyUuid + "-" + systemId;
				Subscription sub = subMap.get(key);
				if(null == sub){
					//不存在,新增
					SubscriptionDto subDto = new SubscriptionDto();
					subDto.setAppId(appId);
					subDto.setAppSecret(appSecret);
					subDto.setCompanyId(company.getId());
					subDto.setCompanyUuid(companyUuid);
					subDto.setSystemId(systemId);
					subDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					subDto.setCreateTime(Calendar.getInstance().getTime());
					subDto.setCreateUserId(1L);
					subDto.setUpdateTime(Calendar.getInstance().getTime());
					subDto.setUpdateUserId(1L);
					subscriptionService.create(subDto);
				}
			}
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setResultMsg("初始化成功!");
		return resDto;
	}

	/**
	 * 初始化微信模板消息
	 * @return
	 */
	public InitDataResDto initWxTemplateMsg(List<String> companyUuids, List<Company> companyList){
		InitDataResDto resDto = new InitDataResDto();
		//初始化公司模板,需要指定公司
		if(null == companyUuids || companyUuids.size() == 0){
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("请填写入参: companyUuids!");
			return resDto;
		}
		//获取所有微信配置
		Map<String, Subscription> subMap = getSubscriptionMap();
		//根据companyUuid获取公司是否开启推送配置
        Map<String, CompanyWxconfig> configMap = getCompanyWxConfigList(companyUuids);

		//已存在的微信模板配置
		Map<String, WxmsgModel> modelMap = getWxMsgModelMap();
		//1、循环匹配公司
		//2、查找公司是否存在模板配置信息
		//3、不存在即添加
		for(Company company: companyList){
			String companId = String.valueOf(company.getId());
			String companyUuid = company.getCompanyUuid();
			String domain = company.getDomain();
			String[] systemIds = {"2", "3"};
			for(String systemId: systemIds){
			    //初始化公司推送配置(默认开启)
                String configKey = companyUuid + "-" + systemId;
                CompanyWxconfig companyWxconfig = configMap.get(configKey);
                if(null  == companyWxconfig) {
                    CompanyWxconfigDto companyWxconfigDto = new CompanyWxconfigDto();
                    companyWxconfigDto.setDomain(domain);
                    companyWxconfigDto.setSystemId(systemId);
                    companyWxconfigDto.setCompanyUuid(companyUuid);
                    companyWxconfigDto.setConfiged(WxConfigEnum.OPEN.getCode());
                    companyWxconfigDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
                    companyWxconfigService.create(companyWxconfigDto);
                }
				//查看是否存在微信配置
				String subKey = companId + "-" + companyUuid + "-" + systemId;
				Subscription sub = subMap.get(subKey);
				if(null == sub){
					continue;
				}
				String[] wxModelTypes = {"1", "2", "3"};
				for(String wxModelType: wxModelTypes){
					String modelKey = subKey + "-" + sub.getId() + "-" + wxModelType;
					WxmsgModel model = modelMap.get(modelKey);
					if(null == model){
						WxmsgModelDto modelDto = new WxmsgModelDto();
						modelDto.setWxModelmsgId("初始化不配,手动去改!");
						if("1".equals(wxModelType)){
							modelDto.setModelTitle(WXModelTypeEnum.NEW_REPORT.getName());
							modelDto.setWxModelType(WXModelTypeEnum.NEW_REPORT.getCode());
						}else if("2".equals(wxModelType)){
							modelDto.setModelTitle(WXModelTypeEnum.AUDIT_REJECT.getName());
							modelDto.setWxModelType(WXModelTypeEnum.AUDIT_REJECT.getCode());
						}else if("3".equals(wxModelType)){
							modelDto.setModelTitle(WXModelTypeEnum.CHANGE_REPORT_STATUS.getName());
							modelDto.setWxModelType(WXModelTypeEnum.CHANGE_REPORT_STATUS.getCode());
						}
						modelDto.setCompanyId(company.getId());
						modelDto.setSubscriptionId(sub.getId());
						modelDto.setCompanyUuid(companyUuid);
						//默认关系,手动去添加wxModelMsgId时打开
						modelDto.setEnabled(0);
						modelDto.setSystemId(sub.getSystemId());
						modelDto.setCreateTime(Calendar.getInstance().getTime());
						modelDto.setUpdateTime(Calendar.getInstance().getTime());
						modelDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
						wxmsgModelService.create(modelDto);
					}
				}
			}
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setResultMsg("初始化成功!");
		return resDto;
	}

    /**
     * 根据companyUuids获取公司是否开启微信推送配置信息
     * @param companyUuids
     * @return
     */
    private Map<String, CompanyWxconfig> getCompanyWxConfigList(List<String> companyUuids) {
        CompanyWxconfigDto companyWxconfigDto = new CompanyWxconfigDto();
        companyWxconfigDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        companyWxconfigDto.setCompanyUuidList(companyUuids);
        List<CompanyWxconfig> list = companyWxconfigService.selectListByDto(companyWxconfigDto);
        Map<String, CompanyWxconfig> map = new HashMap<>(list.size());
        if(null != list && list.size() > 0) {
            for (CompanyWxconfig companyWxconfig : list) {
                String key = companyWxconfig.getCompanyUuid()+"_"+companyWxconfig.getSystemId();
                map.put(key, companyWxconfig);
            }
            return map;
        }
        return map;
    }

    /**
	 * 获取所有微信配置,并以Map形式返回
	 * key格式: companyId-companyUUid-systemId
	 * @return
	 */
	public Map<String, Subscription> getSubscriptionMap(){
		Map<String, Subscription> subMap = new HashMap<>();
		SubscriptionDto subscriptionDto = new SubscriptionDto();
		subscriptionDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<Subscription> subList = subscriptionService.selectListByDto(subscriptionDto);
		if(null == subList && subList.size() == 0){
			return subMap;
		}
		for(Subscription sub: subList){
			String key = sub.getCompanyId() + "-" + sub.getCompanyUuid() + "-" + sub.getSystemId();
			subMap.put(key, sub);
		}
		return subMap;
	}


	/**
	 * 获取所有微信模板配置,并以Map形式返回
	 * key格式: companyId-companyUUid-systemId-subId
	 * @return
	 */
	public Map<String, WxmsgModel> getWxMsgModelMap(){
		Map<String, WxmsgModel> modelMap = new HashMap<>();

		WxmsgModelDto wxmsgModelDto = new WxmsgModelDto();
		wxmsgModelDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<WxmsgModel> wxmsgModelList = wxmsgModelService.selectListByDto(wxmsgModelDto);

		if(null == wxmsgModelList && wxmsgModelList.size() == 0){
			return modelMap;
		}
		for(WxmsgModel model: wxmsgModelList){
			String key = model.getCompanyId() + "-" + model.getCompanyUuid() + "-" + model.getSystemId() + "-" + model.getSubscriptionId() + "-" + model.getWxModelType();
			modelMap.put(key, model);
		}
		return modelMap;
	}

	@Override
	public SendWXMsgAgainResDto sendWXMsgAgain(SendWXMsgAgainReqDto reqDto, String assistantAccessToken) {
		//通知驻场人员审核
		SendWXMsgAgainResDto resDto = new SendWXMsgAgainResDto();
		CustomerPremises cusPre = customerPremisesService.selectById(reqDto.getCustomerPremisesId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		wxTemplateMsgService.sendReportCheckTemplateMsg(assistantAccessToken, reqDto.getCompanyUuid()
				, null, reqDto.getCustomerPremisesId(), String.valueOf(cusPre.getPremisesId())
				, String.valueOf(cusPre.getStaffId())
				, cusPre.getName(), cusPre.getMobile(), sdf.format(cusPre.getVisitProtectTime()));
		return resDto;
	}
}
